<?php

// no direct access
defined('_JEXEC') or die;

jimport('joomla.application.component.modellist');

class AdmissaoModelAdmissoes extends JModelList
{

	public function __construct($config = array())
	{
		if (empty($config['filter_fields'])) {
			$config['filter_fields'] = array(
				'id', 'a.id',
				'prontuario', 'a.prontuario',
				'iniciais', 'a.iniciais',
				'admissao', 'a.admissao',
				'alta', 'a.alta',
				'cidid', 'a.cidid', 'cid_name',
				'created', 'a.created',
				'created_by', 'a.created_by',
			);
		}

		parent::__construct($config);
	}

	protected function populateState($ordering = null, $direction = null)
	{
		// Initialise variables.
		$app = JFactory::getApplication();
		$session = JFactory::getSession();

		// Adjust the context to support modal layouts.
		if ($layout = JRequest::getVar('layout')) {
			$this->context .= '.'.$layout;
		}

		$search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');
		$this->setState('filter.search', $search);

		$authorId = $app->getUserStateFromRequest($this->context.'.filter.author_id', 'filter_author_id');
		$this->setState('filter.author_id', $authorId);
		
		$cidId = $app->getUserStateFromRequest($this->context.'.filter.cid_id', 'filter_cid_id');
		$this->setState('filter.cid_id', $cidId);

		// List state information.
		parent::populateState('a.prontuario', 'asc');
	}

	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id	.= ':'.$this->getState('filter.search');
		$id .= ':'.$this->getState('filter.cid_id');
		$id	.= ':'.$this->getState('filter.author_id');

		return parent::getStoreId($id);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return	JDatabaseQuery
	 * @since	1.6
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db		= $this->getDbo();
		$query	= $db->getQuery(true);
		$user	= JFactory::getUser();

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.id, a.prontuario, a.iniciais, a.admissao, a.alta, a.cidid' .
				', a.created, a.created_by'
			)
		);
		$query->from('#__admissoes AS a');
		
		// Join over the icd10 table.
		$query->select('ic.name AS cid_name');
		$query->join('LEFT', '#__icd10 AS ic ON ic.id = a.cidid');

		// Join over the users for the author.
		$query->select('ua.name AS author_name');
		$query->join('LEFT', '#__users AS ua ON ua.id = a.created_by');
		
		// Filter by a single or group of icd10 codes.
		$cidId = $this->getState('filter.cid_id');
		if (is_numeric($cidId)) {
			$query->where('a.cidid = '.(int) $cidId);
		} else if (is_array($cidId)) {
			JArrayHelper::toInteger($cidId);
			$cidId = implode(',', $cidId);
			$query->where('a.cidid IN ('.$cidId.')');
		}

		// Filter by author
		$authorId = $this->getState('filter.author_id');
		if (is_numeric($authorId)) {
			$type = $this->getState('filter.author_id.include', true) ? '= ' : '<>';
			$query->where('a.created_by '.$type.(int) $authorId);
		}

		// Filter by search in title.
		$search = $this->getState('filter.search');
		if (!empty($search)) {
			if (stripos($search, 'id:') === 0) {
				$query->where('a.id = '.(int) substr($search, 3));
			}
			else if (stripos($search, 'author:') === 0) {
				$search = $db->Quote('%'.$db->getEscaped(substr($search, 7), true).'%');
				$query->where('(ua.name LIKE '.$search.' OR ua.username LIKE '.$search.')');
			}
			else {
				$search = $db->Quote('%'.$db->getEscaped($search, true).'%');
				$query->where('(a.prontuario LIKE '.$search.' OR a.iniciais LIKE '.$search.')');
			}
		}

		// Add the list ordering clause.
		$orderCol	= $this->state->get('list.ordering');
		$orderDirn	= $this->state->get('list.direction');
		if ($orderCol == 'a.iniciais') {
			$orderCol = 'a.iniciais '.$orderDirn.', a.prontuario';
		}
		$query->order($db->getEscaped($orderCol.' '.$orderDirn));

		// echo nl2br(str_replace('#__','jos_',$query));
		return $query;
	}

}
